using System;
using System.Collections.Generic;
using System.Text;
using System.IO.Ports;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using System.Data.SqlClient;

namespace eBirdAttend
{
    class eOfficeTrans
    {
        SerialPort _sPort = new SerialPort();
        RichTextBox _Progress;
        bool _LogFileSts;
        bool _PortSts;
        bool _DispLog;
        int _TimeOut;
        FileInfo _LogFile;
   
        string _strConString;
        Form _ParentForm;
        string _FileName;
        public void Init()
        {
            _DispLog = false;
            _LogFileSts = false;
            _PortSts = false;
            _FileName = "c:\\DlLog.txt";
            

        }
        public void Close()
        {
            try
            {
               
                _sPort.Close();
                _PortSts = false;
            }
            catch (Exception exp)
            {

            }
        }
        public void SetLogFile(string strLogFile)
        {
            _FileName = strLogFile;
            //try
            //{

            //    _LogFile = new FileInfo(strLogFile);
            //    _logWriter = _LogFile.CreateText();
            //    WriteLogLine("Log file\r\n");
            //    _LogFileSts = true;

            //}
            //catch (SystemException exp)
            //{
            //    _LogFileSts = false;
            //}
        }

        public void WriteLog(string strText)
        {
            try
            {

                FileStream fs = new FileStream(_FileName, FileMode.OpenOrCreate | FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                byte[] info = new UTF8Encoding(true).GetBytes(strText);

                fs.Write(info, 0, info.Length);
                fs.Close();
                if (_DispLog)
                {
                    _Progress.Text =  strText+_Progress.Text;

                }
            }
            catch (SystemException exp)
            {

            }

        }
        public bool OpenPort(string strComPort)
        {
            try
            {
                if (_sPort.IsOpen) { WriteLog("Com port already opne\r\n"); }
                _sPort.PortName = strComPort;
                _sPort.BaudRate = 9600;
                _sPort.DataBits = 8;
                _sPort.Parity = Parity.None;
                _sPort.StopBits = StopBits.One;

                _sPort.ReadTimeout = 10;
                _sPort.Handshake = Handshake.None;
                _sPort.ReceivedBytesThreshold = 20;
                _sPort.Open();
                //_sPort.NewLine = "\r";
                _PortSts = true;
                WriteLog("Com port open sucessful\r\n");
                return true;
            }
            catch (SystemException exp)
            {
                WriteLog("****Com port open failed***\r\n");
                _PortSts = false;
                return false;
            }

        }
        public void SetTimeOut(int TimeOutSecs)
        {
            _TimeOut = TimeOutSecs*1000;
        }
        public void SetTextBox(RichTextBox Disp)
        {
            _Progress = Disp;
            _DispLog = true;
        }
        void WriteToPort(string strCMD)
        {
            if (!_sPort.IsOpen) return;
            byte[] byArr = new byte[1];

            for (int i = 0; i < strCMD.Length; ++i)
            {

                byArr[0] = (byte)strCMD[i];
                _sPort.Write(byArr, 0, 1);
                Thread.Sleep(100);

            }
            Thread.Sleep(500);
        }
        public int SendCommand(string strCommand, ref string strRep)
        {
            if (!_sPort.IsOpen) { WriteLog("Port Not Open,Send Command returning\r\n"); return 0; }
            string strLog;
            string strCmd = strCommand.Substring(0, 2);
           
            WriteLog("Sending Command:");
            WriteLog(strCommand);
            WriteLog("\r\n");
            bool TimedOut = false;

            WriteToPort(strCommand);
            while (true)
            {
                try
                {
                    for (int m=0; m < _TimeOut; m += 10)
                    {
                        if (_DispLog) Application.DoEvents();
                        string logMsg = "waiting for response " + m.ToString() + "ms\r\n";
                       // if(m%1000==0)WriteLog(logMsg);
                        try
                        {
                            TimedOut = false;
                            strRep = _sPort.ReadLine();
                        }
                        catch (Exception exp)
                        {
                           // logMsg = "Response not received till  " + m.ToString() + "ms\r\n";
                           // WriteLog(logMsg);
                            if (!_PortSts) return -3;
                            TimedOut = true;
                        }
                        if (!TimedOut) break;
                    }
                    if (TimedOut)
                    {
                        WriteLog("Timeout......");
                        return -2;
                    }
                    strLog = strRep + "\r\n";
                                        
                    WriteLog("Response Rcvd:");
                    WriteLog(strRep);
                    WriteLog("\r\n");

                    if ((strRep.StartsWith(strCmd)) || (strRep.StartsWith("RE")))
                    {
                        if (_LogFileSts)
                        {
                            WriteLog("Positive Reply Command exec Sucess!!!\r\n");
                        }

                        return 1;
                    }
                    if (strRep.StartsWith("FL"))
                    {
                        if (_LogFileSts)
                        {
                            WriteLog("Command exec failed\r\n");
                        }
                        return -1;
                    }
                    continue;
                }
                catch (SystemException exp)
                {
                    WriteLog("Timeout or Read error\r\n");
                    return -2;
                }
            }
        }
        public void SetConnection(string strDbServr, string strDatabase, string strUser, string strPWD)
        {
            _strConString = "Data Source=" + strDbServr;
            _strConString = _strConString + ";Initial Catalog=" + strDatabase;
            _strConString = _strConString + ";User ID=" + strUser;
            _strConString = _strConString + ";Password=" + strPWD;
        }
        delegate void SetGUITextCallBack(string strText);

        void SetGUIText(string strText)
        {         

            //if (_ParentForm.InvokeRequired) /*returns true if we are calling the method from a worker thread.*/
            //{
            //    SetGUITextCallBack visCB = new SetGUITextCallBack(SetGUIText);
            //    this.Invoke(visCB, new object[] { strText });
            //}
            //else
            //{
            //    if (_DispLog)
            //    _Progress.Text = _Progress.Text + strResp;
                
            //}            
        }
        public void DownLoadTrans()
        {
            int i, j;
            int iRetVal;
            string strCmd;
            string strResp, strValues;
            char[] chSpliters = new char[] { ' ', ',', '#' };
            string[] strTockens;
            string strDate;
            string strTime = DateTime.Now.ToLongTimeString();
            if (_strConString == "") { MessageBox.Show("Database Connection details not set"); }
            WriteLog("##########New Download Iteration#########\r\n\r\n");
            WriteLog(strTime + "\r\n");
            try
            {
                //Data Source=DEVIKA;Initial Catalog=eBirdAT;User ID=sa;Password=bmjo
                // string ConnectStr = "Data Source=EBIRD-SER;Initial Catalog=eBirdATS;User ID=sa;Password=bmjo";
                SqlConnection sqlCon = new SqlConnection(_strConString);
                SqlCommand sqlCmd = new SqlCommand();
                DateTime trsTime = new DateTime();
                if (!_sPort.IsOpen) { WriteLog("Serial Port Not open, Cant Continue\r\n"); return; }
                if (_DispLog)
                    _Progress.Text = _Progress.Text + "Start Downloading...";
                trsTime = DateTime.Now;

                strResp = "";
                WriteLog("sql con open\r\n");
               // WriteLog(_strConString);
                sqlCon.Open();
                WriteLog("sql con opened\r\n");
                for (i = 1; i < 10000; ++i)
                {
                    
                    strCmd = "LG " + i.ToString() + "\r";
                    iRetVal = SendCommand(strCmd, ref strResp);
                    if (iRetVal == -1) return;
                    if (iRetVal < 0) continue;
                    if (_DispLog)
                        _Progress.Text = _Progress.Text + strResp;

                    strTockens = strResp.Split(chSpliters);
                    strValues = "insert into TransactionLog (trsCardId,trsINOUT,trsTimeStamp) values(" + strTockens[2].ToString() + ","; //employee id
                    strValues = strValues + strTockens[3].ToString() + ","; //inout 
                    strDate = "'" + strTockens[4] + "/" + strTockens[5] + "/";
                    int logYear;
                    if ((trsTime.Month == 1) && (int.Parse(strTockens[4]) > trsTime.Month))
                        logYear = trsTime.Year - 1;
                    else logYear = trsTime.Year;
                    strTockens[8]= strTockens[8].TrimEnd('\r');
                    strDate = strDate + logYear.ToString() + " ";
                    strDate = strDate + strTockens[6] + ":" + strTockens[7] + ":" + strTockens[8] + "')";
                    strValues = strValues + strDate;
                    sqlCmd.CommandText = strValues;
                    sqlCmd.Connection = sqlCon;
                    WriteLog("executing sql cmd\r\n");
                    sqlCmd.ExecuteNonQuery();
                    WriteLog("sql cmd executed\r\n");

    
                    //System.Windows.Forms.MessageBox.Show(strResp);
                    if (_DispLog) Application.DoEvents();
                    strCmd = "LD " + i.ToString() + "\r";
                    if (SendCommand(strCmd, ref strResp) < 0) continue;
                    if (_DispLog)
                        _Progress.Text = _Progress.Text + strResp;
                }

                sqlCon.Close();
                WriteLog("Closing comport\r\n");
                _sPort.Close();

            }
            catch (Exception exp)
            {
                //_logWriter.Close();
                WriteLog(exp.Message.ToString());
                _sPort.Close();
               // MessageBox.Show(exp.Message.ToString());
              
            }

        }
    }
}